package JMSInternationalEventServer.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.List;

import corbaServer.EventDO;

public class InternationalEventServerDAO
{
	private Connection connection = null;

	public void connect() throws ClassNotFoundException, SQLException
	{
		Class.forName("org.sqlite.JDBC");
		connection = java.sql.DriverManager
				.getConnection("jdbc:sqlite:EventReservationCore/db/jms-db/internationalevents.db");

		System.out.println("Base de datos: nueva conexión."); // registro
	}

	public List<EventDO> getEvents() 
	{
		List<EventDO> events = new ArrayList<EventDO>();
		
		try
		{
			connect();
			
			Statement sentencia = createStatement();
			String query = "SELECT * FROM events";
			ResultSet rs = sentencia.executeQuery(query);
			
			while(rs.next())
			{
//				System.out.println("EventDO = " + rs.getString("Name") + " " + rs.getString("Date") + " " + rs.getString("Description") + " " + rs.getInt("Places"));
			
				events.add(new EventDO(rs.getString("Name"), rs.getString("Date"), rs.getString("Description"), rs.getInt("Places")));
			}

			rs.close();
			sentencia.close();
	  		disconnect();
		} 
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		System.out.println ("Se han devuelto "+events.size()+" eventos."); // registro
		return events;
	}

	public void disconnect() throws SQLException
	{
		checkConnected();
		connection.close();
		System.out.println ("Base de datos: conexión cerrada."); // registro
	}

	private void checkConnected()
	{
		if (connection == null)
			throw new IllegalStateException("A�n no se ha creado la conexi�n a la base de datos");
	}

	private Statement createStatement() throws SQLException
	{
		checkConnected();
		return connection.createStatement();
	}
}
